package com.jh.paymentchannel.service;

import cn.jh.common.utils.CommonConstants;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.jh.paymentchannel.business.BranchbankBussiness;
import com.jh.paymentchannel.business.TopupPayChannelBusiness;
import com.jh.paymentchannel.util.Util;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URI;
import java.util.Map;

/**
 * 支付宝异步通知处理
 */
@Controller
@EnableAutoConfiguration
public class AlipayAppPayCallBackService {

	//TODO 需要开发

	private static final Logger log = LoggerFactory.getLogger(AlipayAppPayCallBackService.class);

    @Value("${alipay.appId}")
    private String appId;

    @Value("${alipay.alipayPubKey}")
    private String publicAlipayKey;

    /**
     * 交易成功
     */
    private static final String TRADE_STATUS_TRADE_SUCCESS = "TRADE_SUCCESS";
/**
    WAIT_BUYER_PAY	交易创建，等待买家付款
    TRADE_CLOSED	未付款交易超时关闭，或支付完成后全额退款
    TRADE_SUCCESS	交易支付成功
    TRADE_FINISHED	交易结束，不可退款
**/
    @Autowired
    private TopupPayChannelBusiness topupPayChannelBusiness;

    @Autowired
    private BranchbankBussiness branchbankBussiness;

    @Autowired
    private Util util;

	@RequestMapping(method=RequestMethod.POST,value="/v1.0/paymentchannel/topup/alipay/apipay/notify_call")
	public @ResponseBody String notifyCall(HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String,String> params) throws IOException{
        log.info("支付宝APP支付异步通知 pay_notify_call --- start#");

/*
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }*/

        //交易状态
        String tradeStatus = (String) params.get("trade_status");

        // 支付尚未完成
        if (!TRADE_STATUS_TRADE_SUCCESS.equals(tradeStatus)) {
            return "";
        }

        //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean signVerified = false;

        try {
            String signType = params.get("sign_type");
            String charset = params.get("charset");
            log.info("开始进行验签处理参数为signType:"+ signType +",params:" + JSONObject.fromObject(params).toString());
            signVerified = AlipaySignature.rsaCheckV1(params, publicAlipayKey, charset,signType);
            log.info("结束验签处理结果为:" + signVerified);

        } catch (AlipayApiException e) {
            log.error("验签失败,",e);
            e.printStackTrace();
        }
        //boolean signVerified = true;

        //验签成功
        if (signVerified) {

            //商户订单号
            String orderCode = (String)params.get("out_trade_no");
            //支付宝订单号
            String aliPayTradeNo = (String)params.get("trade_no");

            RestTemplate restTemplate = new RestTemplate();
            URI uri = util.getServiceUrl("transactionclear", "error url request!");
            String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
            MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
            requestEntity.add("order_code", orderCode);
            String result = restTemplate.postForObject(url, requestEntity, String.class);
            log.info("查询订单信息结果result={}" + result);
            JSONObject jsonObject;
            JSONObject resultObj;

            try {
                jsonObject = JSONObject.fromObject(result);
                resultObj = jsonObject.getJSONObject("result");
            } catch (Exception e) {
                log.error("查询订单信息出错");
                return "没有该订单信息";
            }

            //交易金额
            String totalAmount = (String) params.get("total_amount");
            //交易金额一致性判断
            String orderAmount = resultObj.getString("amount");
            BigDecimal bigTotalAmount = new BigDecimal(totalAmount);
            BigDecimal bigOrderAmount = new BigDecimal(orderAmount);

            //如果金额不一致则报错
            if (bigTotalAmount.compareTo(bigOrderAmount) != 0.) {
                log.info("订单号" + orderCode +",支付宝金额:"+ totalAmount  + ",订单金额" + bigOrderAmount);
                return "交易金额不一致";
            }

            //app_id
            String paramAppId = params.get("app_id");

            if (!appId.equals(paramAppId)) {
                log.info("APPID:" + appId +",支付宝返回APPID:"+ paramAppId  + ",不一致");
                return "appid不一致";
            }



            synchronized (this) {
                log.info("支付宝APP支付异步通知 -- 开始更新订单状态 -- orderCode:" + orderCode);
                // **更新订单状态*//*
                // **调用下单，需要得到用户的订单信息*//*
                restTemplate = new RestTemplate();
                uri = util.getServiceUrl("transactionclear", "error url request!");
                url = uri.toString() + "/v1.0/transactionclear/payment/update";

                MultiValueMap<String, String> requestEntityU = new LinkedMultiValueMap<String, String>();
                requestEntityU.add("status", "1");
                requestEntityU.add("order_code", orderCode);
                requestEntityU.add("third_order_code", aliPayTradeNo);
                result = restTemplate.postForObject(url, requestEntityU, String.class);

                try {
                    jsonObject = JSONObject.fromObject(result);
                    String resp_code = jsonObject.getString(CommonConstants.RESP_CODE);
                    if(resp_code.equals(CommonConstants.SUCCESS)){
                        log.info("支付宝APP支付异步通知 -- 订单状态修改成功====" + result);
                        return "success";
                    } else{
                        log.info("支付宝APP支付异步通知 -- 订单状态修改失败====" + result);
                        return "订单状态修改失败";
                    }
                } catch (Exception e1) {
                    log.error("支付宝APP支付异步通知 pay_notify_call -- 订单状态修改失败====" + e1.getMessage());
                    return "订单状态修改失败";
                }

                //log.info("支付宝异步通知 -- success - 订单已支付! orderCode:" + orderCode);
                //response.getWriter().write("SUCCESS");
            }
        } else {
            return "验签失败";
        }
    }


}
